package org.aceor.mddal.gateway.router.handler;

import org.aceor.mddal.common.sqlparser.result.context.ConditionContext;
import org.aceor.mddal.common.sqlparser.result.context.RouteContext;
import org.aceor.mddal.common.sqlparser.result.context.ShardingContext;
import org.aceor.mddal.common.sqlparser.result.object.Column;
import org.aceor.mddal.gateway.executor.ExecuteContext;
import org.aceor.mddal.gateway.router.RouteHelper;
import org.apache.commons.collections.CollectionUtils;

import java.util.Set;

import static org.aceor.mddal.common.utils.CommonUtil.print;

/**
 * Created by lxue on 16/4/14.
 */
public class JustTBShardingRouteHandler implements RouteHandler{
    @Override
    public ExecuteContext route(RouteHandlerParam param) {
        ExecuteContext executeContext = new ExecuteContext();

        ConditionContext conditionContext = param.sqlParsedResult.conditionContext;
        RouteContext routeContext = param.sqlParsedResult.routeContext;
        ShardingContext shardingContext = param.sqlParsedResult.shardingContext;

        Column column = new Column(
                RouteHelper.findTable(routeContext, shardingContext.logicTableName),
                shardingContext.tbShardingColumn);

        print(JustTBShardingRouteHandler.class, "tb-column:" + column);
        Set<Object> values =
                RouteHelper.getAcceptableValues(
                        conditionContext.getConditionMap().get(column),
                        shardingContext.tbShardingFunction);

        if (CollectionUtils.isEmpty(values)) {
            //TODO: 可以解决的 ==> 考虑算出来的还是字段不存在
            throw new RuntimeException("咱不支持全表查询");
        }

        RouteHelper.setExecuteSqlMapWhenSingleTbOrDbSharding(
                executeContext,
                column,
                values,
                shardingContext,
                routeContext.getSqlBuilder(),
                param.args,
                param.defaultDbIndex);
        return executeContext;
    }
}
